package cn.ham.exception;

import com.sun.org.apache.xpath.internal.operations.String;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author mr.ham
 * @date 2016/11/16 21:48
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public ModelAndView defaultErrorHandler(HttpServletRequest request,Exception ex) throws Exception{
        ModelAndView mav = new ModelAndView();
        mav.addObject("exception", ex);
        mav.addObject("url", request.getRequestURL());
        mav.setViewName("error");
        return mav;
    }

    @ExceptionHandler(value = BusinessException.class)
    @ResponseBody
    public ExceptionInfo<String> jsonErrorHandler(HttpServletRequest request, BusinessException e) throws Exception {
        ExceptionInfo exceptionInfo = new ExceptionInfo<>();
        exceptionInfo.setMsg(e.getMessage());
        exceptionInfo.setCode(ExceptionInfo.ERROR);
        exceptionInfo.setData("error info");
        exceptionInfo.setTime(new Date());
        exceptionInfo.setUrl(request.getRequestURL().toString());
        return exceptionInfo;
    }

}
